#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：arXiv-analyzer
@File    ：logger.py
@IDE     ：PyCharm
@Author  ：iyoahs
@Date    ：2025/6/20 15:06
@Describe：
'''
# !/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：academic_trend_analysis
@File    ：logger.py
@IDE     ：PyCharm
@Author  ：iyoahs
@Date    ：2025/6/20 11:20
@Describe：日志配置
'''

import logging
import os
from datetime import datetime
from typing import Optional


def setup_logger(name: Optional[str] = None, log_level=logging.INFO):
    """配置并返回一个logger实例"""
    logger = logging.getLogger(name or "academic_trend_analysis")
    logger.setLevel(log_level)

    # 创建logs目录如果不存在
    os.makedirs("logs", exist_ok=True)

    # 创建文件处理器
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    log_file = f"logs/academic_analysis_{timestamp}.log"
    file_handler = logging.FileHandler(log_file)
    file_handler.setLevel(log_level)

    # 创建控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(log_level)

    # 创建格式化器
    formatter = logging.Formatter(
        "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S"
    )
    file_handler.setFormatter(formatter)
    console_handler.setFormatter(formatter)

    # 添加处理器到logger
    if not logger.handlers:
        logger.addHandler(file_handler)
        logger.addHandler(console_handler)

    return logger